<?php

use com\gdl\kq\dataobject\attendancegroup\AttendanceGroupDTO;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\kq\interfaces\AttAdminAttendanceGroupServiceIf;
/**
 *  考勤
 *  @author gdl
 */
class api_AttAdminAttendanceGroupService extends api_Abstract implements AttAdminAttendanceGroupServiceIf
{
    /**
     * 添加考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function addAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $result = new ResultDO();
        $data = $attendancegroup->data;
        $globals = new service_globals();
//        $result->success = true;
//        $result->code = 0;
        try {
              $title = $data['title'];
              $setholidaysId = $data['setholidaysId'];
              $platformId = $data['platformId'];
              $goDaysNum = $globals->object_to_array(json_decode($data['goDaysNum']));//['num'=>1,'row'=>['one'=>['startTime'=>123123123,'endTime'=>123123123]]]
              $unusualStatus = $globals->object_to_array(json_decode($data['unusualStatus']));//异常定义 ['beLate'=>[30,60],'leaveEarly'=>[30,60]]
              $coordinateName = $globals->object_to_array(json_decode($data['coordinateName'])); //签到地点标题 ['重庆市重庆市九龙坡区']
              $coordinateTitle = $globals->object_to_array(json_decode($data['coordinateTitle'])); //签到地点名 ['重庆市重庆市九龙坡区']
              $coordinateDeviation = $globals->object_to_array(json_decode($data['coordinateDeviation']));//签到范围  ['500']
              $coordinate = $globals->object_to_array(json_decode($data['coordinate']));//签到点坐标 ['{"lng":106.482009,"lat":29.516761}']
              $groupNotUser = $globals->object_to_array(json_decode($data['groupNotUser']));//['units'=>[1,2,3],'userid'=>[3,5,6]]
              $groupMustUser = $globals->object_to_array(json_decode($data['groupMustUser']));//['units'=>[1,2,3],'userid'=>[3,5,6]]
              $approvalProcessOne = $data['approvalProcessOne'];
              $approvalProcessTwo = $data['approvalProcessTwo'];
              $approvalProcessThree = $data['approvalProcessThree'];
              $offDutyOut = $data['offDutyOut'];//下班是否需要打卡 1打卡 2不打卡
              $faceStatus = $data['faceStatus'];
              $trackLocation = $data['trackLocation'];
              $type = $data['type'];
              $unitId = $data['unitId'];
//              $adminUserId = $data['adminUserId'];

            // 参数处理 start
                //签到点坐标
                $rule=array(); //规则
                for($i=0;$i<count($coordinateTitle);$i++){
                    $deviation =  is_numeric($coordinateDeviation[$i]) ? number_format($coordinateDeviation[$i], 2, '.', '') : 1500;
                    if($deviation>99000 || $deviation==0){
                        $deviation = 99900.0;
                    }
                    //                    $deviation = $deviation*1000;

                    $coordinateDeviation[$i] = $deviation;
                    $addcoordinate = htmlspecialchars_decode($coordinate[$i]);
                    $rule[] = ['title'=>$coordinateTitle[$i],'deviation'=>$coordinateDeviation[$i],'name'=>$coordinateName[$i],'coordinate'=>json_decode($addcoordinate,true)];
                }
                $coordinateS = serialize($rule);

                if($type==1){
                    //上下班次数
                    $goDaysNum = serialize($goDaysNum);
                    //异常定义
                    $unusualStatus = serialize($unusualStatus);
                    /*****************/
                    $row = [
                        'title'=>$title,
                        'setholidaysId'=>$setholidaysId,
                        'platformId'=>$platformId,
                        'goDaysNum'=>$goDaysNum,
                        'unusualStatus'=>$unusualStatus,
                        'groupMustUser'=>serialize($groupMustUser),
                        'groupNotUser'=>serialize($groupNotUser),
                        'coordinate'=>$coordinateS,
                        'approvalProcessOne'=>$approvalProcessOne,
                        'approvalProcessTwo'=>$approvalProcessTwo,
                        'approvalProcessThree'=>$approvalProcessThree,
                        'offDutyOut'=>$offDutyOut,
                        'faceStatus'=>$faceStatus,
                        'trackLocation'=>$trackLocation,
                        'unitId'=>$unitId,
                        'createTime'=>time(),
                    ];
                }else{
                    /*****************/
                    $row = [
                        'title'=>$title,
                        'platformId'=>$platformId,
                        'coordinate'=>$coordinateS,
                        'faceStatus'=>$faceStatus,
                        'type'=>2,
                        'createTime'=>time(),
                    ];
                }

            $attendancegroupModel = new model_attendance_attendancegroup();
            $id = $attendancegroupModel->insert($row);
            if ($id){
                $this->changeGroupUnitIdsUserIds($id,$groupMustUser,$groupNotUser);
                if ($type==1)$this->disposeGroupUserMemberArr($id,$platformId,$groupMustUser,$groupNotUser,$title,$setholidaysId,$goDaysNum);
                $result->code = 1;
                $result->success = true;
                $result->message = 1;
            }else{
                $result->code = 0;
                $result->success = true;
                $result->message = '数据添加失败';
            }

            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '未知错误';
        }
        return $result;
    }

    /**
     * 修改考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function editAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $result = new ResultDO();
        $data = $attendancegroup->data;
        $id = $attendancegroup->id?getStr($attendancegroup->id):0;
        $globals = new service_globals();
//        $result->success = true;
//        $result->code = 0;
        try {
              $title = $data['title'];
              $setholidaysId = $data['setholidaysId'];
              $platformId = $data['platformId'];
              $goDaysNum = $globals->object_to_array(json_decode($data['goDaysNum']));//['num'=>1,'row'=>['one'=>['startTime'=>123123123,'endTime'=>123123123]]]
              $unusualStatus = $globals->object_to_array(json_decode($data['unusualStatus']));//异常定义 ['beLate'=>[30,60],'leaveEarly'=>[30,60]]
              $coordinateTitle = $globals->object_to_array(json_decode($data['coordinateTitle'])); //签到地点名 ['重庆市重庆市九龙坡区']
              $coordinateName = $globals->object_to_array(json_decode($data['coordinateName'])); //签到地点标题 ['重庆市重庆市九龙坡区']
              $coordinateDeviation = $globals->object_to_array(json_decode($data['coordinateDeviation']));//签到范围  ['500']
              $coordinate = $globals->object_to_array(json_decode($data['coordinate']));//签到点坐标 ['{"lng":106.482009,"lat":29.516761}']
              $groupNotUser = $globals->object_to_array(json_decode($data['groupNotUser']));//['units'=>[1,2,3],'userid'=>[3,5,6]]
              $groupMustUser = $globals->object_to_array(json_decode($data['groupMustUser']));//['units'=>[1,2,3],'userid'=>[3,5,6]]
              $approvalProcessOne = $data['approvalProcessOne'];
              $approvalProcessTwo = $data['approvalProcessTwo'];
              $approvalProcessThree = $data['approvalProcessThree'];
              $offDutyOut = $data['offDutyOut'];//下班是否需要打卡 1打卡 2不打卡
              $faceStatus = $data['faceStatus'];
              $trackLocation = $data['trackLocation'];
              $type = $data['type'];
//              $adminUserId = $data['adminUserId'];

            // 参数处理 start
                //签到点坐标
                $rule=array(); //规则
                for($i=0;$i<count($coordinateTitle);$i++){
                    $deviation =  is_numeric($coordinateDeviation[$i]) ? number_format($coordinateDeviation[$i], 2, '.', '') : 1500;
                    if($deviation>99000 || $deviation==0){
                        $deviation = 99900.0;
                    }
                    //                    $deviation = $deviation*1000;

                    $coordinateDeviation[$i] = $deviation;
                    $addcoordinate = htmlspecialchars_decode($coordinate[$i]);
                    $rule[] = ['title'=>$coordinateTitle[$i],'name'=>$coordinateName[$i],'deviation'=>$coordinateDeviation[$i],'coordinate'=>json_decode($addcoordinate,true)];
                }
                $coordinateS = serialize($rule);

                if($type==1){
                    //上下班次数
                    $goDaysNum = serialize($goDaysNum);
                    //异常定义
                    $unusualStatus = serialize($unusualStatus);
                    /*****************/
                    $row = [
                        'title'=>$title,
                        'setholidaysId'=>$setholidaysId,
                        'platformId'=>$platformId,
                        'goDaysNum'=>$goDaysNum,
                        'unusualStatus'=>$unusualStatus,
                        'groupMustUser'=>serialize($groupMustUser),
                        'groupNotUser'=>serialize($groupNotUser),
                        'coordinate'=>$coordinateS,
                        'approvalProcessOne'=>$approvalProcessOne,
                        'approvalProcessTwo'=>$approvalProcessTwo,
                        'approvalProcessThree'=>$approvalProcessThree,
                        'offDutyOut'=>$offDutyOut,
                        'faceStatus'=>$faceStatus,
                        'trackLocation'=>$trackLocation,
                        'createTime'=>time(),
                    ];
                }else{
                    /*****************/
                    $row = [
                        'title'=>$title,
                        'platformId'=>$platformId,
                        'coordinate'=>$coordinateS,
                        'faceStatus'=>$faceStatus,
                        'type'=>2,
                        'createTime'=>time(),
                    ];
                }

            $attendancegroupModel = new model_attendance_attendancegroup();
            $attendancegroupModel->update($row," id = {$id} ");
            if ($id){
                $this->changeGroupUnitIdsUserIds($id,$groupMustUser,$groupNotUser);
                if ($type==1)$this->disposeGroupUserMemberArr($id,$platformId,$groupMustUser,$groupNotUser,$title,$setholidaysId,$goDaysNum);
                $result->code = 1;
                $result->success = true;
                $result->message = 1;
            }else{
                $result->code = 0;
                $result->success = true;
                $result->message = '数据添加失败';
            }

            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '未知错误';
        }
        return $result;
    }

    /**
     * 操作考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function operationAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $result = new ResultDO();
        $data = $attendancegroup->data;
        $id = $attendancegroup->id?getStr($attendancegroup->id):0;
        $globals = new service_globals();
//        $result->success = true;
//        $result->code = 0;
        try {
            $title = $data['title'];
            $do = $data['do'];
            $setholidaysId = $data['setholidaysId'];
            $platformId = $data['platformId'];
            $goDaysNum = $globals->object_to_array(json_decode($data['goDaysNum']));//['num'=>1,'row'=>['one'=>['startTime'=>123123123,'endTime'=>123123123]]]
            $unusualStatus = $globals->object_to_array(json_decode($data['unusualStatus']));//异常定义 ['beLate'=>[30,60],'leaveEarly'=>[30,60]]
            $coordinateTitle = $globals->object_to_array(json_decode($data['coordinateTitle'])); //签到地点名 ['重庆市重庆市九龙坡区']
            $coordinateDeviation = $globals->object_to_array(json_decode($data['coordinateDeviation']));//签到范围  ['500']
            $coordinate = $globals->object_to_array(json_decode($data['coordinate']));//签到点坐标 ['{"lng":106.482009,"lat":29.516761}']
            $groupNotUser = $globals->object_to_array(json_decode($data['groupNotUser']));//['units'=>[1,2,3],'userid'=>[3,5,6]]
            $groupMustUser = $globals->object_to_array(json_decode($data['groupMustUser']));//['units'=>[1,2,3],'userid'=>[3,5,6]]
            $approvalProcessOne = $data['approvalProcessOne'];
            $approvalProcessTwo = $data['approvalProcessTwo'];
            $approvalProcessThree = $data['approvalProcessThree'];
            $offDutyOut = $data['offDutyOut'];//下班是否需要打卡 1打卡 2不打卡
            $faceStatus = $data['faceStatus'];
            $trackLocation = $data['trackLocation'];
            $type = $data['type'];
//              $adminUserId = $data['adminUserId'];

            // 参数处理 start
            //签到点坐标
            $rule=array(); //规则
            for($i=0;$i<count($coordinateTitle);$i++){
                $deviation =  is_numeric($coordinateDeviation[$i]) ? number_format($coordinateDeviation[$i], 2, '.', '') : 1500;
                if($deviation>99000 || $deviation==0){
                    $deviation = 99900.0;
                }
                //                    $deviation = $deviation*1000;

                $coordinateDeviation[$i] = $deviation;
                $addcoordinate = htmlspecialchars_decode($coordinate[$i]);
                $rule[] = ['title'=>$coordinateTitle[$i],'deviation'=>$coordinateDeviation[$i],'coordinate'=>json_decode($addcoordinate,true)];
            }
            $coordinateS = serialize($rule);

            if($type==1){
                //上下班次数
                $goDaysNum = serialize($goDaysNum);
                //异常定义
                $unusualStatus = serialize($unusualStatus);
                /*****************/
                $row = [
                    'title'=>$title,
                    'setholidaysId'=>$setholidaysId,
                    'platformId'=>$platformId,
                    'goDaysNum'=>$goDaysNum,
                    'unusualStatus'=>$unusualStatus,
                    'groupMustUser'=>serialize($groupMustUser),
                    'groupNotUser'=>serialize($groupNotUser),
                    'coordinate'=>$coordinateS,
                    'approvalProcessOne'=>$approvalProcessOne,
                    'approvalProcessTwo'=>$approvalProcessTwo,
                    'approvalProcessThree'=>$approvalProcessThree,
                    'offDutyOut'=>$offDutyOut,
                    'faceStatus'=>$faceStatus,
                    'trackLocation'=>$trackLocation,
                    'createTime'=>time(),
                ];
            }else{
                /*****************/
                $row = [
                    'title'=>$title,
                    'platformId'=>$platformId,
                    'coordinate'=>$coordinateS,
                    'faceStatus'=>$faceStatus,
                    'type'=>2,
                    'createTime'=>time(),
                ];
            }

            $attendancegroupModel = new model_attendance_attendancegroup();
            $id = $attendancegroupModel->update($row," id = {$id} ");
            if ($id){
                if ($type==1)$this->disposeGroupUserMemberArr($id,$platformId,$groupMustUser,$groupNotUser,$title,$setholidaysId,$goDaysNum);
                $result->code = 1;
                $result->success = true;
                $result->message = 1;
            }else{
                $result->code = 0;
                $result->success = true;
                $result->message = '数据添加失败';
            }

            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '未知错误';
        }
        return $result;
    }

    /**
     * 删除考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function deleteAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $id = $attendancegroup->id ? gdl_lib_BaseUtils::getStr($attendancegroup->id) : 0;
        $result = new ResultDO();
        $result->success = true;
        $result->message = "您已删除，请勿重复操作";
        $result->code = 400;
        $result->data = [];
//        if(empty($platformId)){
//            $result->message = "您还没有选择平台";
//            return $result;
//        }
        if(empty($id)){
            $result->message = "参数错误";
            return $result;
        }
        try{
            $attendancegroupModel = new model_attendance_attendancegroup();
            $where = " id = {$id} ";
            $res = $attendancegroupModel->update($where," isDelete=1");
            if($res){
                $result->code = 200;
                $result->message = "已删除";
            }
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    /**
     * 处理添加或者修改时 考勤组人员的变更
     * @param $agid
     * @param $platformId
     * @param $groupMustUser
     * @param $groupNotUser
     * @return bool
     */
    public function disposeGroupUserMemberArr($agid,$platformId,$groupMustUser,$groupNotUser,$agName,$setholidaysId,$goDaysNum){
        $id = $agid;//考勤组ID
        $rowNums = 0;//总人数
        $attendanceGroupUserModel = new model_attendance_attendancegroupuser();
        $memberModel = new model_attendance_member();
        //参与考勤人员 ['units'=>[1,2,3],'userid'=>[3,5,6]]
        $useridsMustAll = '';
        //获取选择的人员ID
        if (!empty($groupMustUser['userid'])){
            $useridsMust = implode(',',$groupMustUser['userid']);
            $useridsMustAll = $useridsMust;
        }
        //根据架构获取所有人员
        if (!empty($groupMustUser['units'])){
            $unitsMust = implode(',',$groupMustUser['units']);
            $memberCondition = " unitid in ({$unitsMust}) ";
            $mustMemberids = $memberModel->select($memberCondition,'id')->items;
            $mustMemberids = $mustMemberids?implode(',',array_column($mustMemberids,'id')):"";
            $useridsMustAll = !empty($useridsMustAll)?($mustMemberids?$useridsMustAll.','.$mustMemberids:$useridsMustAll):$mustMemberids;
        }
        //考勤组人员档案表
        $groupmemberrecordModel = new model_attendance_groupmemberrecord();
        $setholidaysModel = new model_attendance_setholidays();
        $setholidaysRow = $setholidaysModel->selectOne(" id = {$setholidaysId} ",'workday,specialWorkday,holiday');//查询节假日定义
        $groupmemberrecordModel->insert(
            [
                'memberIds'=>$useridsMustAll,
                'agId'=>$id,
                'agName'=>$agName,
                'status'=>1,
                'date'=>date('Y-m-d',time()),
                'workday'=>$setholidaysRow['workday'],
                'specialWorkday'=>$setholidaysRow['specialWorkday'],
                'holiday'=>$setholidaysRow['holiday'],
                'goDaysNum'=>$goDaysNum,
            ]
        );

        //排除每个架构中 和 选定的人员中已经参加考勤组的人员 并踢出之前的考勤组
        $groupMustCondition = " platformId =$platformId  and memberId in ($useridsMustAll) and type = 1 ";
        $sureMustMemberids = $attendanceGroupUserModel->select($groupMustCondition,'id')->items;
        if (!empty($sureMustMemberids)){
            $sureMustMemberids = implode(',',array_column($sureMustMemberids,'id'));
            $attendanceGroupUserModel->delete( " id in ({$sureMustMemberids}) ");
        }
        $useridsMustAll = explode(',',$useridsMustAll);
        $rowNums = $rowNums+count($useridsMustAll);
        foreach ($useridsMustAll as $userVar){
            $attendanceGroupUserModel->insert(
                [
                    'agId'=>$id,
                    'memberId'=>$userVar,
                    'type'=>1,
                    'platformId'=>$platformId,
                    'createTime'=>time(),
                    'status'=>0,
                ]
            );
        }
        //无需考勤人员
        $useridsNotAll = '';
        //获取选择的人员ID
        if (!empty($groupNotUser['userid'])){
            $useridsNot = implode(',',$groupNotUser['userid']);
            $useridsNotAll = $useridsNot;
        }
        //根据架构获取所有人员
        if (!empty($groupNotUser['units'])){
            $unitsNot = implode(',',$groupNotUser['units']);
            $memberCondition = " unitid in ({$unitsNot}) ";
            $notMemberids = $memberModel->select($memberCondition,'id')->items;
            $notMemberids = $notMemberids?implode(',',array_column($notMemberids,'id')):"";
            $useridsNotAll = !empty($useridsNotAll)?($notMemberids?$useridsNotAll.','.$notMemberids:$useridsNotAll):$notMemberids;
        }

        //排除每个架构中 和 选定的人员中已经无需参加考勤组的人员 并踢出之前的考勤组
        $groupNotCondition = " platformId =$platformId  and memberId in ($useridsNotAll) and type = 2 ";
        $sureNotMemberids = $attendanceGroupUserModel->select($groupNotCondition,'id')->items;
        if (!empty($sureNotMemberids)){
            $sureNotMemberids = implode(',',array_column($sureNotMemberids,'id'));
            $attendanceGroupUserModel->delete( " id in ({$sureNotMemberids}) ");
        }
        $useridsNotAll = explode(',',$useridsNotAll);
        $rowNums = $rowNums+count($useridsNotAll);
        foreach ($useridsNotAll as $userVar){
            $attendanceGroupUserModel->insert(
                [
                    'agId'=>$id,
                    'memberId'=>$userVar,
                    'type'=>2,
                    'platformId'=>$platformId,
                    'createTime'=>time(),
                    'status'=>0,
                ]
            );
        }

        $attendancegroupModel = new model_attendance_attendancegroup();
        $attendancegroupModel->update(['id'=>$id],['number'=>$rowNums]);
        return true;
    }

    //储存修改考勤组和单位、人员的关系
    private function changeGroupUnitIdsUserIds($agId,$groupMustUser,$groupNotUser){
        if (!$agId)return false;
        $groupunituser = new model_attendance_groupunituser();
        $mustUnitids = implode(',',$groupMustUser['units']);
        $mustUserids = implode(',',$groupMustUser['userid']);
        $notUnitids = implode(',',$groupNotUser['units']);
        $notUserids = implode(',',$groupNotUser['userid']);

        //查找之前考勤组是否有相同单位ID和人员ID 有的话删除
        //type:1需参与考勤  2不需参与考勤 status:1单位 2人员
        $groupunituser->delete(" status=1 and unitId in ({$mustUnitids}) and type=1  ");
        $groupunituser->delete(" status=2 and memberId in ({$mustUserids}) and type=1  ");
        $groupunituser->delete(" status=1 and unitId in ({$notUnitids}) and type=2  ");
        $groupunituser->delete(" status=2 and memberId in ({$notUserids}) and type=2  ");
        $data['agId'] = $agId;
        foreach ($groupMustUser['units'] as $key => $value) {
            $data['status'] = 1;
            $data['type'] = 1;
            $data['unitId'] = $value;
            $groupunituser->insert($data);
        }
        foreach ($groupMustUser['userid'] as $key => $value) {
            $data['status'] = 2;
            $data['type'] = 1;
            $data['memberId'] = $value;
            $groupunituser->insert($data);
        }
        foreach ($groupNotUser['units'] as $key => $value) {
            $data['status'] = 1;
            $data['type'] = 2;
            $data['unitId'] = $value;
            $groupunituser->insert($data);
        }
        foreach ($groupNotUser['userid'] as $key => $value) {
            $data['status'] = 2;
            $data['type'] = 2;
            $data['unitId'] = $value;
            $groupunituser->insert($data);
        }
        return true;
    }

    //考勤组列表
    public function getAdminAttendanceGroupList(AttendanceGroupDTO $attendancegroup){
        #接受参数
        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";
        $offset = $attendancegroup->offset ? gdl_lib_BaseUtils::getStr($attendancegroup->offset, 'int') : 0;
        $num = $attendancegroup->num ? gdl_lib_BaseUtils::getStr($attendancegroup->num, 'int') : 10;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];

        #验证
        if(empty($data)){$result->message = "缺少必要条件"; return $result;}
        $platformId = $data['platformId']?$data['platformId']:0;
        $adminUserId = $data['adminUserId']?$data['adminUserId']:0;
        $adminReg    = $data['adminReg']?$data['adminReg']:'';
        #条件
        $where = " platformId ={$data['platformId']} AND isdelete = 0  ";
        if (isset($data['type']) && $data['type']==1){
            $where .= " AND type = {$data['type']} ";
        }elseif(isset($data['type']) && $data['type']==2){
            $where .= " AND type = {$data['type']} ";
        }else{
            $where .= " AND type = 1 ";
        }

        if (isset($data['title']) && !empty($data['title']))$where .= " AND title like '%{$data['title']}%' ";
        if (isset($data['departmenName']) && !empty($data['departmenName']))$where .= " AND departmenName like '%{$data['departmenName']}%' ";
        if (isset($data['id']) && !empty($data['id']))$where .= " AND id = {$data['id']}";
        if (isset($data['unitId']) && !empty($data['unitId']))$where .= " AND unitId = {$data['unitId']} ";
        //根据管理员ID获取所有单位ID

        $userServiceModel =  new service_user();
//        $unitIdsList = $userServiceModel->getMemberUnitsRelation($platformId,$adminUserId,2);
        $groupunituser = new model_attendance_groupunituser();
        $appadminuser = new model_lhbase_appadminuser();
        $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
//        print_r($adminUserId);die;
        if (!$appadminuserInfo){
            $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
            $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ",'attendancegroupId')->items;

            if ($attendancegroupIds){
                $attendancegroupIds = array_column($attendancegroupIds,'attendancegroupId');
                $attendancegroupIds = implode(',',$attendancegroupIds);
                $where .= " and id in ({$attendancegroupIds}) ";
            }else{
                $result->message = "暂无数据";
                $result->code = 200;
                $result->data = [];
                $result->counts = 0;
                return $result;
            }
        }

        #分页
        if($offset=='0') $offset=1;
        $limit = ($offset - 1) * $num . "," . $num;
        $group = 'order by id desc limit '.$limit;
        $count = 0;
        try{
            $List = [];
            #数据
            $attendancegroupModel = new model_attendance_attendancegroup();
            $groupFiled = "id,title,number,groupMustUser,platformId,unitId";
            $join = "";
            if($data['status']==1){//  1只返回考勤组名称 2只返回单位名称 3只返回组织名称列表
                $groupFiled = "id,title";
                $group = '';
            }
            $groupWhere = $where;
            $List = $attendancegroupModel->select($groupWhere, $groupFiled, $group,"",$join)->items;

            $count = $attendancegroupModel->selectOne($groupWhere, "count(id) num");
            $count = !empty($count['num'])?$count['num']:0;
            if ($data['status']==2){// 1只返回考勤组名称 2只返回单位名称 3只返回组织名称列表
//                if (!$appadminuserInfo){
//                    $condition = "";
//                }else{
//                    $condition = "";
//                }
//                $groupunituser->select($condition);
            }elseif ($data['status']==3){

            }
            if ($List){
                #数据
                /****获取单位名字*****/
                $unitsModel = new model_lhbase_units();
                foreach ($List as &$oo){
                    $unit_name = $unitsModel->selectOne(['id'=>$oo['unitId']],'unitName');
                    $oo['unitName'] = $unit_name['unitName'];
                }
            }

            if (isset($List[0]['groupMustUser'])){
                foreach ($List as &$value){
                    $groupMustUser = [
                        'units' =>
                            array (
                            ),
                        'userid' =>
                            array (
                            )
                    ];
                    $groupNotUser = [
                        'units' =>
                            array (
                            ),
                        'userid' =>
                            array (
                            )];
                    $unituserList = $groupunituser->select(" agId = {$value['id']} ")->items;

                    foreach ($unituserList as $uulV){
                        if ($uulV['type']==1 and $uulV['status']==1){
                            $groupMustUser['units'][] = $uulV['unitId'];
                        }elseif ($uulV['type']==1 and $uulV['status']==2){
                            $groupMustUser['userid'][] = $uulV['memberId'];
                        }elseif ($uulV['type']==2 and $uulV['status']==1){
                            $groupNotUser['units'][] = $uulV['unitId'];
                        }elseif ($uulV['type']==2 and $uulV['status']==2){
                            $groupNotUser['userid'][] = $uulV['memberId'];
                        }
                    }

                    $value['groupMustUser'] = serialize($groupMustUser);
                    $value['groupNotUser'] = serialize($groupNotUser);
                }
            }
            # 处理数据
            if($List){
                $result->message = "获取成功";
                $result->code = 200;
                $result->data = $List;

            }else{
                $result->message = "暂无数据";
            }

        }catch(Exception $ex){
            $result->message = $ex->getMessage();
        }
        $result->counts = $count;
        return $result;
    }

    /**
     * 获取当前用户上面有几级
     */
    public function getPlatformManagementLevel(AttendanceGroupDTO $attendancegroup){
        #接受参数
        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";
        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];

        #验证
        $platformId =  $data['platformId'];
//        $unitid =  $data['unitid'];
        if(empty($platformId)){$result->message = "缺少必要条件"; return $result;}
//        if(empty($unitid)){$result->message = "缺少必要条件"; return $result;}

        try{

            $List = [];
            #数据
            $unitsModel = new model_lhbase_units();
            $level = $unitsModel->selectOne("platformId='{$platformId}'  and isDelete=1","id,level",'order by level desc'); //获取低于当前层级的数据
            if ($level){
                $num = $level['level'];
                for($i=0;$i<$num;$i++){
                    if ($i==0){
                        $List[$i] = ['name'=>"直接主管","level"=>1,"type"=>"target_management"];
                    }else{
                        $List[$i] =  ['name'=>"第".($i+1)."级主管","level"=>($i+1),"type"=>"target_management"];
                    }
                }
            }else{
                $List[0] = ['name'=>"直接主管","level"=>1,"type"=>"target_management"];
            }

            # 处理数据
            if($List){
                #数据
                $result->message = "获取成功";
                $result->code = 200;
                $result->data = $List;
            }else{
                $result->message = "暂无数据";
            }

        }catch(Exception $ex){
            $result->message = $ex->getMessage();
        }

        return $result;
    }


}
